import jwt
import requests
from datetime import datetime

def decode_token(token):
    """解码JWT token"""
    try:
        # 使用JWT_SECRET_KEY解码
        secret_key = 'jwt-secret-key'  # 从配置中获取
        decoded = jwt.decode(token, secret_key, algorithms=['HS256'])
        return decoded
    except jwt.ExpiredSignatureError:
        print("❌ Token已过期")
        return None
    except jwt.InvalidTokenError as e:
        print(f"❌ Token无效: {e}")
        return None

def test_token_with_api(token):
    """使用token测试API"""
    url = "http://localhost:5001/api/users/"
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    params = {
        "page": 1,
        "per_page": 10,
        "search": ""
    }
    
    try:
        response = requests.get(url, headers=headers, params=params)
        print(f"API响应状态码: {response.status_code}")
        print(f"API响应内容: {response.text}")
        return response.status_code == 200
    except Exception as e:
        print(f"API请求失败: {e}")
        return False

def check_token_from_browser():
    """从浏览器localStorage获取token进行测试"""
    print("请从浏览器开发者工具的Console中运行以下命令获取token:")
    print("localStorage.getItem('token')")
    print("\n然后将token粘贴到这里进行测试")
    
    token = input("请输入token: ").strip()
    
    if not token:
        print("❌ 未提供token")
        return
    
    print(f"\n=== Token信息 ===")
    print(f"Token长度: {len(token)}")
    print(f"Token前50个字符: {token[:50]}...")
    
    # 解码token
    decoded = decode_token(token)
    if decoded:
        print(f"Token解码成功:")
        print(f"  - Subject (用户ID): {decoded.get('sub')}")
        print(f"  - 过期时间: {datetime.fromtimestamp(decoded.get('exp'))}")
        print(f"  - 签发时间: {datetime.fromtimestamp(decoded.get('iat'))}")
        print(f"  - 当前时间: {datetime.now()}")
        
        # 检查是否过期
        if decoded.get('exp') < datetime.now().timestamp():
            print("❌ Token已过期")
        else:
            print("✅ Token未过期")
            
            # 测试API
            print(f"\n=== 测试API ===")
            success = test_token_with_api(token)
            if success:
                print("✅ API调用成功")
            else:
                print("❌ API调用失败")
    else:
        print("❌ Token解码失败")

if __name__ == "__main__":
    check_token_from_browser() 